package com.shiyi.utils;

import com.shiyi.exception.BusinessException;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

//文件转换工具
public class FileUtils {

    /**
     * 将网络文件转换为文件流
     * @return
     */
    public static MultipartFile downloadAsMultipartFile(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            byte[] fileBytes = outputStream.toByteArray();

            // 生成随机文件名
            String fileName = UUID.randomUUID().toString() + getFileExtension(urlString);

            // 使用Spring的MockMultipartFile类来模拟MultipartFile对象
            return new MockMultipartFile(
                    "file", // 表单中的字段名
                    fileName, // 文件名
                    "application/octet-stream", // Content-Type，这里使用通用类型，或者从响应头中获取
                    fileBytes // 文件内容
            );
        } finally {
            connection.disconnect();
        }
    }

    // 根据URL获取文件扩展名（简单示例，可能不适用于所有情况）
    private static String getFileExtension(String urlString) {
        String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex > 0) {
            return fileName;
        }
        return ""; // 没有扩展名则返回空字符串
    }
}

